import React, { useState, useEffect } from 'react';
import axios from 'axios';

const EducationInfoForm = ({ applicationId }) => {
    const [educationInfos, setEducationInfos] = useState([]);
    const [newEducationInfo, setNewEducationInfo] = useState({
        schoolName: '',
        educationType: '',
        major: '',
        degree: '',
        graduationDate: '',
        graduationCertificateNo: '',
        degreeCertificateNo: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchEducationInfos = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/education-info`);
                setEducationInfos(response.data);
            } catch (error) {
                console.error('Error fetching education info:', error);
            }
        };

        if (applicationId) {
            fetchEducationInfos();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewEducationInfo(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/education-info/${editingId}`, newEducationInfo);
                alert('学历学位信息更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/education-info`, newEducationInfo);
                alert('学历学位信息添加成功！');
            }
            setNewEducationInfo({
                schoolName: '',
                educationType: '',
                major: '',
                degree: '',
                graduationDate: '',
                graduationCertificateNo: '',
                degreeCertificateNo: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/education-info`);
            setEducationInfos(response.data);
        } catch (error) {
            console.error('Error saving education info:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewEducationInfo(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/education-info/${id}`);
            alert('学历学位信息删除成功！');
            setEducationInfos(educationInfos.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting education info:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>个人学历学位信息</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>学校名称:</label>
                    <input type="text" name="schoolName" value={newEducationInfo.schoolName} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>学历类型:</label>
                    <input type="text" name="educationType" value={newEducationInfo.educationType} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>专业:</label>
                    <input type="text" name="major" value={newEducationInfo.major} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>学位:</label>
                    <input type="text" name="degree" value={newEducationInfo.degree} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>毕业时间:</label>
                    <input type="date" name="graduationDate" value={newEducationInfo.graduationDate} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>毕业证书编号:</label>
                    <input type="text" name="graduationCertificateNo" value={newEducationInfo.graduationCertificateNo} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>学位证书编号:</label>
                    <input type="text" name="degreeCertificateNo" value={newEducationInfo.degreeCertificateNo} onChange={handleChange} />
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加学历学位信息</h4>
            <table>
                <thead>
                    <tr>
                        <th>学校名称</th>
                        <th>学历类型</th>
                        <th>专业</th>
                        <th>学位</th>
                        <th>毕业时间</th>
                        <th>毕业证书编号</th>
                        <th>学位证书编号</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {educationInfos.map(info => (
                        <tr key={info.id}>
                            <td>{info.schoolName}</td>
                            <td>{info.educationType}</td>
                            <td>{info.major}</td>
                            <td>{info.degree}</td>
                            <td>{info.graduationDate}</td>
                            <td>{info.graduationCertificateNo}</td>
                            <td>{info.degreeCertificateNo}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default EducationInfoForm;

